# -*- coding: UTF-8 -*-
# wordpress import from xml files
# imports a wordpress xml file to blogmaker
"""
I have get some problems dealing with the following entities. As a workarround just find an replace them:
    &raquo; »
    &laquo; « 
    &nbps; 
"""

import sys
import os
from django.utils.encoding import smart_str
# just add the project folder to the python_path
sys.path.append('..')
sys.path.append('../..')
os.environ['DJANGO_SETTINGS_MODULE']='trespams.settings' # your settings configuration
xml_file = 'backup.xml' # your wordpress export file
site_id = 1 # your site
django_content_type_id = 12

from lxml import etree
from blogmaker.blog.models import *
from blogmaker.comments.models import *
weblog = etree.parse(xml_file)
WP_NAMESPACES = {'wp': "http://wordpress.org/export/1.0/",
                 'content':"http://purl.org/rss/1.0/modules/content/"
                 }


"""Obtains wp categories that would map into blog tags"""
def import_categories_to_tags():
    categories = [categoria.text for categoria in
            weblog.xpath('//wp:cat_name',
                namespaces=WP_NAMESPACES)]
    for category in categories:
        new_tag = Tag(tag = category)
        new_tag.save()
        print category
        

def import_posts():
    posts = [post for post in weblog.findall('channel/item')]
    for post in posts:
        title =  post.xpath('title')[0].text
        status = post.xpath('wp:status',namespaces=WP_NAMESPACES)[0].text
        print "Adding : %s" % title #headline
        
        new_post = Entry()
        new_post.id = int(post.xpath('wp:post_id', namespaces=WP_NAMESPACES)[0].text)
        new_post.slug=post.xpath('wp:post_name',namespaces=WP_NAMESPACES)[0].text
        new_post.pub_date = post.xpath('wp:post_date',namespaces=WP_NAMESPACES)[0].text
        new_post.headline = title
        new_post.active= status == 'publish'
        content = post.xpath('content:encoded',namespaces=WP_NAMESPACES)[0].text
        new_post.body_markdown = smart_str(content)
        new_post.save()
        
        # coments                
        for comment in post.xpath('wp:comment',namespaces=WP_NAMESPACES):
            author = comment.xpath('wp:comment_author',namespaces=WP_NAMESPACES)[0].text
            print "\t adding comment from comment_author: %s" % author
            new_comment = Comment()
            new_comment.id = int(comment.xpath('wp:comment_id',namespaces=WP_NAMESPACES)[0].text)
            new_comment.content_type_id = int(django_content_type_id)
            new_comment.object_id = int(new_post.id)
            new_comment.submit_date= comment.xpath('wp:comment_date',namespaces=WP_NAMESPACES)[0].text            
            new_comment.is_public = (comment.xpath('wp:comment_approved',namespaces=WP_NAMESPACES)[0].text=="1")           
            new_comment.ip_address= comment.xpath('wp:comment_author_IP',namespaces=WP_NAMESPACES)[0].text
            if  comment.xpath('wp:comment_author_url',namespaces=WP_NAMESPACES)[0].text:
                new_comment.person_www=u"%s" % comment.xpath('wp:comment_author_url',namespaces=WP_NAMESPACES)[0].text
            else:
                new_comment.person_www=""
            new_comment.site_id = site_id
            new_comment.pub_date=comment.xpath('wp:comment_date',namespaces=WP_NAMESPACES)[0].text
            new_comment.person_name=comment.xpath('wp:comment_author',namespaces=WP_NAMESPACES)[0].text
            if comment.xpath('wp:comment_author_email',namespaces=WP_NAMESPACES)[0].text:
                new_comment.person_email=u"%s" % comment.xpath('wp:comment_author_email',namespaces=WP_NAMESPACES)[0].text
            else:
                new_comment.person_email =""
                        
            comment_type = comment.xpath('wp:comment_type',namespaces=WP_NAMESPACES)[0].text
            if comment_type:
                # its a trackback
                new_comment.comment_type = 'trackback'
                try:
                    trackback_info= new_comment.person_name.split('#')
                    if len(trackback_info) == 3:
                        blog = trackback_info[0]                    
                        title = trackback_info[2]                    
                    elif len(trackback_info) == 2:
                        blog = trackback_info[0]                    
                        title = trackback_info[1]       
                    else:
                        blog = new_comment.person_name
                        title= new_comment.person_name                                     
                except:
                    print  "Error unpacking :%s, it could be spam" % new_comment.person_name
                    blog = new_comment.person_name
                    title= new_comment.person_name
                new_comment.trackback_name=u"%s" % blog
                new_comment.trackback_title=u"%s" % title
                new_comment.trackback_www=new_comment.person_www
            else:
                new_comment.comment_type="comment"
           
            if comment.xpath('wp:comment_content',namespaces=WP_NAMESPACES)[0].text:
                new_comment.comment= u"%s" % comment.xpath('wp:comment_content',namespaces=WP_NAMESPACES)[0].text
                new_comment.save()
            else:
                new_comment= None
            
            # Cagegories    
            categories=post.xpath('category')                
            for category in categories:
                tag, created = Tag.objects.get_or_create(tag=u'%s'%category.text)                
                if created:
                    print "Creating tag %s" % tag.tag
                new_post.tags.add(tag)
            if categories:
                new_post.save()
        
if __name__=="__main__":
    import_posts()
    #import_categories_to_tags()
